//
//  TTGoodsNewListViewController.m
//  TaoTuo
//
//  Created by LG on 2020/10/28.
//  Copyright © 2020 刘广. All rights reserved.
//

#import "TTGoodsListViewController.h"
#import <JXPagingView/JXPagerView.h>
#import <JXCategoryView.h>
#import "TTGoodsListView.h"
#import "TTMessageViewController.h"
#import "UIViewController+LLPanBack.h"
#import "TTSearchViewController.h"

@interface TTGoodsListViewController ()<JXCategoryViewDelegate, JXCategoryListContainerViewDelegate, JXCategoryListContentViewDelegate>
{
    CGFloat JXheightForHeaderInSection;
}

@property (nonatomic, strong) UIButton *topBtn;
@property (nonatomic, copy) NSString *searchName;
@property (nonatomic, strong) NSMutableDictionary *paramsDic;  // 参数
@property (nonatomic, assign) NSInteger selectIndex;    // 选中哪个
@property (nonatomic, strong) JXCategoryTitleView *categoryTitleView;
@property (nonatomic, strong) JXCategoryListContainerView *listContainerView;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSMutableArray *listViews;
@property (nonatomic, strong) UIImage *shadowImage;

@property (nonatomic, assign) NSInteger currentIndex;   ///当前第几个
@property (nonatomic, strong) UIButton *toTopBtn;   /// 点击滚到顶部
/// 存所有参数{0:{}, 1:{}}
@property (nonatomic, strong) NSMutableDictionary *totalDic;
/// 搜索名称
@property (nonatomic, strong) NSMutableDictionary *searchNameDic;

@end

@implementation TTGoodsListViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.shadowImage = self.navigationController.navigationBar.shadowImage;
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.shadowImage = self.shadowImage;
}

- (instancetype)initWithSearchName:(NSString *)searchName paramsDic:(NSDictionary *)paramsDic selectIndex:(NSInteger)selectIndex
{
    self = [super init];
    if (self) {
        
        if (paramsDic == nil) {
            NSNumber *num = [searchName isEqualToString:@"女戒"] ? @(1) : @(2);
            self.paramsDic = @{
                               @"param.sourceType" : num,
                               @"param.categoryName" : searchName
                               }.mutableCopy;
        } else {
            self.paramsDic = paramsDic.mutableCopy;
        }
        if (selectIndex >= [[self class] getAllCategoryTitles].count) {
            selectIndex = 0;
        }
        self.selectIndex = selectIndex;
        
        self.searchName = searchName;
        NSArray *array = [[self class] getAllCategoryTitles];
        if (![searchName containsString:array[selectIndex]]) {
            self.searchName  = [NSString stringWithFormat:@"%@ %@", array[selectIndex], searchName];
        }
        
        [self.totalDic setObject:self.paramsDic forKey:@(selectIndex)];
        [self.searchNameDic setObject:self.searchName forKey:@(selectIndex)];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColor.whiteColor;
    
    /// 搜索条件变化了，设置搜索名称
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchNameChangedNotify:) name:@"searchNameChangedNotify_key" object:nil];
    
    
    [self setupSubviews];
}

- (void)searchNameChangedNotify:(NSNotification *)notify
{
    NSString *categoryName = self.titles[self.currentIndex];
    NSString *searchNameStr = notify.object;
    if (![searchNameStr containsString:categoryName]) {
        searchNameStr = [NSString stringWithFormat:@"%@ %@", categoryName, searchNameStr];
    }
    self.searchNameDic[@(self.currentIndex)] = searchNameStr;
    [self.topBtn setTitle:searchNameStr forState:UIControlStateNormal];
}

+ (NSArray *)getAllCategoryTitles
{
    return @[@"全部", @"女戒", @"套链", @"对戒", @"男戒", @"吊坠", @"手链", @"手镯", @"耳钉", @"耳线", @"耳坠"];;
}

- (void)clickTopSearchBtn
{
//    TTMessageViewController *messageVC;
//    BOOL has = NO;
//    for (UIViewController *vc in self.navigationController.viewControllers) {
//        if ([vc isKindOfClass:[TTMessageViewController class]]) {
//            messageVC = (TTMessageViewController *)vc;
//            has = YES;
//            break;
//        }
//    }
//    if (!has) {
//        messageVC = [[TTMessageViewController alloc] init];
//        messageVC.categoryName = [self.searchName componentsSeparatedByString:@" "].firstObject;
//        [self.navigationController pushViewController:messageVC animated:YES];
//    } else {
//        [self.navigationController popToViewController:messageVC animated:YES];
//    }
    
    TTSearchViewController *searchVC = [[TTSearchViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchVC];
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [[LLRouteTool getCurrentNavigationController] presentViewController:nav animated:YES completion:nil];
    
}


- (void)setupSubviews
{
    // titleView
    UIButton *topBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    topBtn.frame = CGRectMake(0, 7, 300 * kScale, 30);
    topBtn.backgroundColor = UIColorHex(F0F4F7);
    [topBtn setImage:[UIImage imageNamed:@"good_list_search"] forState:UIControlStateNormal];
    [topBtn setTitle:self.searchName forState:UIControlStateNormal];
    [topBtn setTitleColor:UIColorHex(999999) forState:UIControlStateNormal];
    topBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    topBtn.layer.cornerRadius = 15;
    [topBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [topBtn addTarget:self action:@selector(clickTopSearchBtn) forControlEvents:UIControlEventTouchUpInside];
    topBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    topBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    self.navigationItem.titleView = topBtn;
    self.topBtn = topBtn;
    
    JXheightForHeaderInSection = 50;
    
    self.titles = [[self class] getAllCategoryTitles];
    self.categoryTitleView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, JXheightForHeaderInSection)];
    self.categoryTitleView.delegate = self;
    self.categoryTitleView.titles = self.titles;
    [self.view addSubview:self.categoryTitleView];
    self.categoryTitleView.contentEdgeInsetLeft = 20;        // 左边距
    self.categoryTitleView.contentEdgeInsetRight = 20;       // 右边距
    self.categoryTitleView.titleSelectedColor = UIColorHex(333333);
    self.categoryTitleView.titleColor = UIColorHex(808080);
    self.categoryTitleView.titleLabelZoomEnabled = NO;
    self.categoryTitleView.titleFont = [UIFont systemFontOfSize:15];
    self.categoryTitleView.titleSelectedFont = [UIFont boldSystemFontOfSize:16];
    self.categoryTitleView.cellSpacing = 35;
    
    
    JXCategoryIndicatorLineView *lineView = [[JXCategoryIndicatorLineView alloc] init];
    lineView.indicatorColor = UIColorHex(9B71FF);
    lineView.indicatorHeight = 6;
    lineView.verticalMargin = 6;
    lineView.indicatorWidth = 22;
    lineView.indicatorCornerRadius = 3;
    self.categoryTitleView.indicators = @[lineView];
    
    
    _listContainerView = [[JXCategoryListContainerView alloc] initWithDelegate:self];
    _listContainerView.frame = CGRectMake(0, JXheightForHeaderInSection, SCREEN_WIDTH, self.view.height - StatusBarAndNavBar_Height - JXheightForHeaderInSection);
    [self.view addSubview:_listContainerView];
    
    self.categoryTitleView.contentScrollView = self.listContainerView.scrollView;
    [self addPanGestureRecognizerToView:self.listContainerView.scrollView];
    // 默认选中哪个
    _categoryTitleView.defaultSelectedIndex = self.selectIndex;
    _listContainerView.defaultSelectedIndex = self.selectIndex;
    
    if (self.listViews.count == 0) {
        
        for (int i = 0; i < self.titles.count; i++) {
            TTGoodsListView *listView = [[TTGoodsListView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.listContainerView.height)];
            [self.listViews addObject:listView];
            @weakify(self)
            listView.searchParamsChangedBlock = ^(NSDictionary * _Nonnull params) {
                @strongify(self)
                self.paramsDic = params.mutableCopy;
            };
        }
        
    }
    
}

#pragma mark - JXCategoryViewDelegate
- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index {
    
    self.currentIndex = index;
    TTGoodsListView *listView = (TTGoodsListView *)self.listViews[index];
    self.toTopBtn.hidden = listView.collectionView.contentOffset.y < 2000;
    listView.hiddenScreening = index == 0;
    listView.isAll = index == 0;
    
    [listView.leftFiltrateView.rightView setupViewsWithName:self.titles[index]];
    NSString *searchNameStr = self.searchNameDic[@(index)];
    [self.topBtn setTitle:searchNameStr forState:UIControlStateNormal];
    
}

- (void)categoryView:(JXCategoryBaseView *)categoryView didScrollSelectedItemAtIndex:(NSInteger)index {
//    NSLog(@"%@", NSStringFromSelector(_cmd));
}

- (void)categoryView:(JXCategoryBaseView *)categoryView didClickSelectedItemAtIndex:(NSInteger)index {
    [self.listContainerView didClickSelectedItemAtIndex:index];
}

- (void)categoryView:(JXCategoryBaseView *)categoryView scrollingFromLeftIndex:(NSInteger)leftIndex toRightIndex:(NSInteger)rightIndex ratio:(CGFloat)ratio {
    [self.listContainerView scrollingFromLeftIndex:leftIndex toRightIndex:rightIndex ratio:ratio selectedIndex:categoryView.selectedIndex];
}

#pragma mark - JXCategoryListContainerViewDelegate

- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    self.currentIndex = index;
    NSMutableDictionary *dic = self.totalDic[@(index)];
    if (dic == nil) {
        dic = [NSMutableDictionary dictionary];
        dic[@"param.sourceType"] = @3;
    }
    
    NSString *searchNameStr = self.searchNameDic[@(index)];
    if (searchNameStr.length == 0) {
        searchNameStr = self.titles[index];
        self.searchNameDic[@(index)] = searchNameStr;
    }
    [self.topBtn setTitle:searchNameStr forState:UIControlStateNormal];
    
    TTGoodsListView *listView = (TTGoodsListView *)self.listViews[index];
    if (index == 0) {
//        [self.paramsDic removeObjectForKey:@"param.categoryName"];
        [dic removeObjectForKey:@"param.categoryName"];
    } else {
//        self.paramsDic[@"param.categoryName"] = self.titles[index];
        dic[@"param.categoryName"] = self.titles[index];
    }
    
    listView.hiddenScreening = index == 0;
    listView.isAll = index == 0;
    
    [listView.leftFiltrateView.rightView setupViewsWithName:self.titles[index]];
    [listView setType:index params:dic];
    
    @weakify(self)
    listView.scrollEnd = ^(CGFloat offsetY) {
        @strongify(self)
        self.toTopBtn.hidden = offsetY < 2000;
    };
    listView.scrollToTopBlock = ^{
        @strongify(self)
        self.toTopBtn.hidden = YES;
    };
    
    return listView;
}

- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return self.titles.count;
}


- (UIView *)listView
{
    return self.view;
}
    

- (NSMutableArray *)listViews
{
    if (!_listViews) {
        _listViews = [NSMutableArray array];
    }
    return _listViews;
}

- (void)toTopBtnClick
{
    TTGoodsListView *listView = (TTGoodsListView *)self.listViews[self.currentIndex];
    [listView.collectionView scrollToTopAnimated:YES];
}


- (UIButton *)toTopBtn
{
    if (!_toTopBtn) {
        _toTopBtn = [UIButton createButtonWithImage:[UIImage imageNamed:@"zhiding"] target:self action:@selector(toTopBtnClick)];
        _toTopBtn.frame = CGRectMake(self.view.width - 50, self.view.height - 50, 40, 40);
        _toTopBtn.hidden = YES;
        _toTopBtn.backgroundColor = [UIColor whiteColor];
        _toTopBtn.layer.cornerRadius = 20;
        _toTopBtn.layer.shadowColor = [UIColor blackColor].CGColor;
        _toTopBtn.layer.shadowOffset = CGSizeZero;
        _toTopBtn.layer.shadowOpacity = 0.3;
        [self.view addSubview:_toTopBtn];
    }
    return _toTopBtn;
}
    


- (NSMutableDictionary *)totalDic
{
    if (!_totalDic) {
        _totalDic = [NSMutableDictionary dictionary];
    }
    return _totalDic;
}

- (NSMutableDictionary *)searchNameDic
{
    if (!_searchNameDic) {
        _searchNameDic = [NSMutableDictionary dictionary];
    }
    return _searchNameDic;
}



@end
